import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { INestApplication } from '@nestjs/common';

/**
 * Swagger 文档服务
 * 基于 NestJS 官方文档实现
 * 参考: https://docs.nestjs.cn/recipes/swagger
 */
@Injectable()
export class SwaggerService {
  constructor(private readonly configService: ConfigService) {}

  /**
   * 初始化 Swagger 文档
   */
  setupSwagger(app: INestApplication) {
    const swaggerConfig = this.configService.get('swagger');

    if (!swaggerConfig.enabled) {
      return;
    }

    const config = new DocumentBuilder()
      .setTitle(swaggerConfig.title)
      .setDescription(swaggerConfig.description)
      .setVersion(swaggerConfig.version)
      .addBearerAuth(
        {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
          name: 'JWT',
          description: 'Enter JWT token',
          in: 'header',
        },
        'JWT-auth',
      )
      .addTag('认证管理', '用户认证相关接口')
      .addTag('系统管理', '系统配置相关接口')
      .addTag('用户管理', '用户管理相关接口')
      .addTag('文档', 'API 文档相关接口')
      .build();

    const document = SwaggerModule.createDocument(app, config);

    // 设置 Swagger UI 选项
    const options = {
      swaggerOptions: {
        persistAuthorization: true,
        displayRequestDuration: true,
        filter: true,
        showExtensions: true,
        showCommonExtensions: true,
      },
    };

    SwaggerModule.setup('api-docs', app, document, options);
  }

  /**
   * 获取 Swagger 文档 JSON
   */
  getDocument(app: INestApplication) {
    const config = new DocumentBuilder()
      .setTitle(this.configService.get('swagger.title') || 'WWJCloud API')
      .setDescription(
        this.configService.get('swagger.description') ||
          'WWJCloud API Documentation',
      )
      .setVersion(this.configService.get('swagger.version') || '1.0.0')
      .addBearerAuth()
      .build();

    return SwaggerModule.createDocument(app, config);
  }
}
